#! /bin/sh  
# chkconfig: 345 99 10
# -------------------------------------------------------------------------
# Fichier : dbora
#
# Auteur : LMR
# Societe: ASTEK
# Date : 27/01/2014
# Application : CC-RC
# Version : 1.0.0
# Description : Arret/redemarrage des bases oracle au boot
# Emplacement : etc/initd/rcd
#
#
# Modifications :
#	1.0.0 <27/01/2014> <LMR> : <Creation>
# -------------------------------------------------------------------------

#
# Save LD_LIBRARY_PATH
SAVE_LLP=$LD_LIBRARY_PATH
#
#
DATE=`date "+%d%m%y_%H%M%S"`
START_FILE=$HOME/start.${USER}_${DATE}.log
STOP_FILE=$HOME/stop.${USER}_${DATE}.log
#
#
# Set this in accordance with the platform
ORATAB=/etc/oratab
#
#
if [ ! $ORATAB ] ; then
  echo "Set ORATAB to dir where oratab file is located"
  exit 1;
fi

#Function to stop databases
stopDb() {
$ORACLE_HOME/bin/sqlplus /nolog << EOF
connect / as sysdba
SHUTDOWN IMMEDIATE;
EXIT;
EOF

  if test $? -eq 0 ; then
	echo ""
    echo "${INST} \"${ORACLE_SID}\" shut down."
  else
	echo ""
    echo "${INST} \"${ORACLE_SID}\" not shut down."
  fi
}

#Function to start databases
startDb() {
$ORACLE_HOME/bin/sqlplus /nolog << EOF
connect / as sysdba
STARTUP;
EXIT;
EOF

  if test $? -eq 0 ; then
	echo ""
	echo "${INST} \"${ORACLE_SID}\" startup."
  else
	echo ""
    echo "${INST} \"${ORACLE_SID}\" not startup."
  fi
}


#
# Loop for every entry in oratab file 
#
# Following loop 'Database Instance[s]' with 'Y' entry

cat $ORATAB | while read LINE
do
  case $LINE in
  \#*)                ;;        #comment-line in oratab
  *)
  ORACLE_SID=`echo $LINE | awk -F: '{print $1}' -`

  if [ "$ORACLE_SID" = '*' ] ; then
      # NULL SID - ignore
      ORACLE_SID=""
      continue
  fi
  # Proceed only if last field is 'Y' or 'W'
  if [ "`echo $LINE | awk -F: '{print $NF}' -`" = "Y" ] ; then
    if [ `echo $ORACLE_SID | cut -b 1` != '+' ]; then
		INST="Database instance"
		ORACLE_HOME=`echo $LINE | awk -F: '{print $2}' -`      
		#Variables 
		ORA_NLS33=$ORACLE_HOME/ocommon/nls/admin/data	  
		ORA_NLS10=$ORACLE_HOME/nls/data
		PATH=${PATH}:$ORACLE_HOME/bin
		LD_LIBRARY_PATH=${SAVE_LLP}:${ORACLE_HOME}/lib
		HOST=`hostname`
		PLATFORM=`uname`
		
		export ORACLE_HOME ORA_NLS33 ORA_NLS10 LD_LIBRARY_PATH  PATH ORACLE_SID #NLS_LANG
	  	  
		#Gestion arret/demarrage 
		#
		case $1 in
		'start')
				LOG=$START_FILE
				echo "Processing $ORACLE_SID"				
				startDb >> $LOG 2>&1
				;;
		'stop')
				LOG=$STOP_FILE
				echo "Processing $ORACLE_SID"					
				stopDb >> $LOG 2>&1
				;;
		*)
				echo "usage: $0 {start|stop}"
				exit
				;;
		esac
		#
	  
    fi
  fi
  ;;
  esac
done

echo "Traitement termine ==> log file $LOG"	
exit